/**
 * ChelloTraffic widget
 * (C) 2006-2007, Sebestyén Gábor
 *
 * Project Home: http://code.google.com/p/chellotraffic/
 */

/*
 * Global variables
 */
var isGadget = !!(System && System.Gadget); // Microsoft SideBar Gadget
var isWidget = !!(window.widget);           // Apple Dashboard widget
var RES_IMAGES_PREFIX = "Images/";
var MAX_WIDTH = 315;			            // maximum width of tx_traffic item
var TRAFFIC_BAR_OFFSET = 0				    /* 8 */;


// is AJAX request running?
var isRunning;


// this function borrowed from prototype.js
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return element;
}



// add debug support
if (isGadget) {
    function debug(msg) {
        System.Debug.outputString(msg);
    }
}



// option name, option id, limit in MB
var PACKS = new Array(
	{display: "MINIMUM", name: "minimum", max: 250*1024},
	{display: "MEDIUM", name: "medium", max: 250*1024},
	{display: "EXTREME", name: "extreme", max: 250*1024},
	{display: "PROFESSIONAL", name: "pro", max: 250*1024}
);
var PACK_DEFAULT = 2;

var last_traffic = null;
var	current_ver = null;



if (isGadget) {
    System.Gadget.settingsUI = "settings.html";
    System.Gadget.onSettingsClosing  = function(event) {
        if (event.closeAction == event.Action.commit) {
            System.Gadget.Settings.writeString("id", $('name_input').value);
            System.Gadget.Settings.writeString("pwd", $('pwd_input').value);

            var pname = $('chello_popup').value;
            System.Gadget.Settings.writeString("pack", pname);
        }
        // Allow the Settings dialog to close.
        event.cancel = false;
    };
}

// invoked by document load event of settings.html
function initSettings() {
    if (isGadget) {
        $('name_input').value = System.Gadget.Settings.readString("id");
        $('pwd_input').value = System.Gadget.Settings.readString("pwd");
        $('chello_popup').value = PACKS[getIndexForPack(getDefaultPack())].name;
        
        // show version
        $('ver_label').innerHTML = "ChelloTraffic " + System.Gadget.version;
    }
}


// invoked by document load event of ChelloTraffic.html
function load()
{
	// put your setup code here...
	isRunning = false;

	// set version
	if (isWidget) {
	    current_ver = widget.system('/usr/bin/ruby read_ver.rb', null).outputString;
	} else if(isGadget) {
	    // read version from my XML file
	    current_ver = System.Gadget.version;
	}

    // set version
    // widget only
    var verLabel = $("ver_label");
	if (verLabel) {
	    verLabel.innerHTML = "ChelloTraffic " + current_ver;
	}

	reset();

	doMainTask();
}

function remove()
{
	// your widget has just been removed from the layer
	// remove any preferences as needed
	// widget.setPreferenceForKey(null, "your-key");
}

function hide()
{
	// your widget has just been hidden stop any timers to
	// prevent cpu usage
}

function show()
{
	// your widget has just been shown.  restart any timers
	// and adjust your interface as needed
}

function showBack(event)
{
	// your widget needs to show the back

	var front = $("front");
	var back = $("back");

	if (isWidget)
		widget.prepareForTransition("ToBack");

	front.style.display="none";
	back.style.display="block";
	
	if (window.widget)
		setTimeout('widget.performTransition();', 0);


	// my code
	if (isWidget) {
		var val;

		val = widget.preferenceForKey('id');
		if (val != null)
		$("name_input").value = val;

		val = widget.preferenceForKey('pwd');
		if (val != null)
		$("pwd_input").value = val;
	}
}

function showFront(event)
{
	// your widget needs to show the front

	var front = $("front");
	var back = $("back");

	if (window.widget)
		widget.prepareForTransition("ToFront");

	front.style.display="block";
	back.style.display="none";
	
	if (window.widget)
		setTimeout('widget.performTransition();', 0);
}




/*
* My Functions
*/

function doMainTask() {
	getTraffic();
	checkNewVersion();
}


// ChelloTraffic web client
var ctwClient = null;


function getTraffic()
{
	if (isRunning == false) {
		// reset widgets
		reset();

        var cid = null, pwd = null;
        if (isWidget) {
		    cid = widget.preferenceForKey('id');
		    pwd = widget.preferenceForKey('pwd');
		} else if (isGadget) {
		    cid = System.Gadget.Settings.readString('id');
		    pwd = System.Gadget.Settings.readString('pwd');
		} else {
		    return;
		}
		if (cid != null && pwd != null && cid.length > 0) {
			// start anim
			startRefreshAnim();

			isRunning = true;

			// execute ruby robot to get the traffic
			/// widget.system('/usr/bin/ruby traffic.rb ' + cid + ' ' + pwd, cmd_handler);
		    ctwClient = new CTWebClient(cid, pwd);
		    ctwClient.onsuccess = function(client, data) {
		        // alert("ChelloTraffic: OK, month = " + data.currentMonth);
		        setTraffic(data.currentMonth);

		        isRunning = false;
            	stopRefreshAnim();
		    };
		    ctwClient.onerror = function(client, err, message) {
                switch(err) {
                    case 2:
       					$('tx_traffic').innerText = "HIBA: Rossz név vagy jelszó.";
    					break;
                    case 3:
            			$('tx_traffic').innerHTML = "HIBA: Érvénytelen tanusítvány miatt a kérés megtagadva.";
                        break;
                    default:
            			$('tx_traffic').innerHTML = "HIBA: " + message;
                        break;
                }

		        isRunning = false;
            	stopRefreshAnim();
		    };
		    ctwClient.start();
		} else {
			$('tx_traffic').innerHTML = "HIBA: Kitöltetlen név vagy jelszó!";
		}
	} else {
		if (last_traffic != null) {
			setTraffic(last_traffic);
		} else {
			// reset widgets
			reset();
		}
	}
}

function cmd_handler(result)
{
	isRunning = false;

	var r = result.outputString;
	
	if (r == null) {
		// CRASH: call of external script failed
		$('tx_traffic').innerText = "HIBA: belső hiba..";
	} else {
		// parse output
		var v = r.match(/^err:(\w+)/)

		if (v != null) {
			switch (v[1]) {
				case "login":
					$('tx_traffic').innerText = "HIBA: Rossz név vagy jelszó.";
					break;
				case "failed":
					$('tx_traffic').innerText = "HIBA: Érvénytelen adatkérés.";
					break;
				default:
					$('tx_traffic').innerText = "Ismeretlen hiba.";
					break;
			}
		} else {
			var n = parseInt(r);
			last_traffic = n;
			setTraffic(n);
		}
	}


	// stop anim
	// FIXME: should this calling be the last? It seems it suspends execution of following commands.
	stopRefreshAnim();
}

/*
* Backside events
*/

function setIdent() {
	var obj = $('name_input');
	if (isWidget)
    	widget.setPreferenceForKey(obj.value, 'id');
	if (isGadget)
        System.Debug.outputString('id', obj.value);
}

function setPassword() {
	var obj = $('pwd_input');
	if (isWidget)
    	widget.setPreferenceForKey(obj.value, 'pwd');
	if (isGadget)
        System.Debug.outputString('pwd', obj.value);
}

function setChelloPack(elem) {
	var chosenOption = elem.options[elem.selectedIndex].value;
	
	// display selection in front
	$("tx_packname").innerHTML = PACKS[getIndexForPack(chosenOption)].display;

	// Other code that handles the menu selection change
	if (isWidget)
	    widget.setPreferenceForKey(chosenOption, 'pack');
	if (isGadget)
        System.Debug.outputString('pack', chosenOption);
}

// returns default Chello package name
function getDefaultPack() {
    var p = null;
    if (isWidget) {
	    p = widget.preferenceForKey('pack');
    } else if (isGadget) {
        p = System.Gadget.Settings.readString('pack');
    }

    if (p == null || p == "") {
	    // set default if not set yet
	    p = PACKS[PACK_DEFAULT].name;
	    if (isWidget)
    	    widget.setPreferenceForKey(p, 'pack');
    	if (isGadget)
    	    System.Gadget.Settings.writeString('pack', p);
    }
	return p;
}

function getIndexForPack(name)
{
	if (name == null)
	return -1;

	var k = 0;
	for (i=0; i<PACKS.length; i++)
	{
		if (PACKS[i].name == name) {
			return k;
		}
		k++;
	}
	return -1;
}

// reset info
function reset() {
	var bar = $('traffic_bar');

	bar.style.visibility = "hidden";

	$('tx_traffic').style.color = "white";
	$('tx_traffic').innerText = "-";

	// set pack limit
	var ix = getIndexForPack(getDefaultPack());
	if (ix != -1) {
		$('tx_packname').innerHTML = PACKS[ix].display;
		$('tx_limit').innerHTML = String(PACKS[ix].max / 1024) + " GB";
	} else {
		$('tx_packname').innerHTML = "??";
		$('tx_limit').innerHTML = "?? GB";
	}
}

function setTraffic(actual)
{
	var bar = $('traffic_bar');
	var w;  // bar width
	var px = TRAFFIC_BAR_OFFSET; // bar left offset


    // current Chello subscription
    var pack = PACKS[getIndexForPack(getDefaultPack())];

    // get maximum bar width
    var w_max = $('traffic_frame').style.width || MAX_WIDTH;

	var max_chello = pack.max;
	if (actual > max_chello) {
		w = (max_chello * w_max) / actual;

		px = TRAFFIC_BAR_OFFSET + w;
		w = w_max - w;
		$('tx_traffic').style.color = "#800000";
	} else {
		w = (actual * w_max) / max_chello;
		$('tx_traffic').style.color = "#FFFFFF";
	}

	// bar.src = RES_IMAGES_PREFIX + "ribbon_red.png";
	bar.style.left = px + "px";
	bar.style.width = w + "px";
	bar.style.visibility = "visible";

	if (actual == 0) {
		$('tx_traffic').innerHTML = "0 MB (0\%)";
	} else {
		$('tx_traffic').innerHTML = actual + " MB (" + ((actual * 100) / max_chello).toFixed(1) + "\%)";
	}
	// set pack limit
	$('tx_packname').innerHTML = pack.display;
	$('tx_limit').innerHTML = String(pack.max / 1024) + " GB";
}



/*
 * Actions
 */

function doShowHome() {
    if (isWidget) {
    	widget.openURL('https://kezeles.chello.hu/');
    } else if (isGadget || window.open) {
    	window.open('https://kezeles.chello.hu/');
    }
}


function doDownloadNewVersion() {
    if (isWidget) {
        widget.openURL('http://code.google.com/p/chellotraffic/files/ChelloTraffic-' + document.getElementById('current_label').innerHTML + '.wdgt.zip', '_blank');
    } else if (isGadget) {
        window.open('http://code.google.com/p/chellotraffic/files/ChelloTraffic-' + document.getElementById('current_label').innerHTML + '.gadget', '_blank');
    } else {
        window.open('http://code.google.com/p/chellotraffic/files/', '_blank');
    }
}

function doRefresh() {
	doMainTask();
}



/*
 * Refresh animation
 */

var refresh_anim = {firstElement:null, timer:null, phase:0};

function startRefreshAnim() {
	if (refresh_anim.timer != null)
	{
		clearInterval(refresh_anim.timer);
		refresh_anim.timer  = null;
	}

	refresh_anim.firstElement = $('refresh_button');
	refresh_anim.timer = setInterval("doAnimateRefresh();", 250);
	refresh_anim.phase = 0;
	doAnimateRefresh();
}

function stopRefreshAnim() {
	if (refresh_anim.timer != null)
	{
		clearInterval(refresh_anim.timer);
		refresh_anim.timer  = null;
	}
	$('refresh_button').src = RES_IMAGES_PREFIX + "refresh.png";
	$('refresh_button').style.width = "36px";
	$('refresh_button').style.height = "37px";
}


function doAnimateRefresh() {
	
	refresh_anim.firstElement.src = RES_IMAGES_PREFIX + "refresh" + refresh_anim.phase + ".png";
	refresh_anim.firstElement.style.width = "37px";
	refresh_anim.firstElement.style.height = "36px";
	refresh_anim.phase = (refresh_anim.phase + 1) % 5;
}



/*
 * Helper - XMLHttpRequest object getter
 */
function getHTTPClient() {
    var xmlhttp;

    if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
    } else {
    	xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}


/*
* New Version Management
*/

function checkNewVersion() {
    var xmlhttp = getHTTPClient();

	var url = "http://chellotraffic.googlecode.com/svn/trunk/versions.txt";
	xmlhttp.open("GET", url);
	xmlhttp.setRequestHeader("Cache-Control", "no-cache");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4) {
			if (xmlhttp.status==200) {
			    var site_ver = current_ver;

			    var verRe = null;
			    if (isGadget)
    			    verRe = new RegExp("gadget=([0-9\.]+)");
    			if (isWidget)
        			verRe = new RegExp("widget=([0-9\.]+)");

			    var m = verRe.exec(xmlhttp.responseText);
			    if (m) {
			        site_ver = m[1];
			    }
				// var site_ver = xmlhttp.responseText.replace(/\s+$/g, "");

				if (current_ver == site_ver) {
					$("nv_frame").style.display = "none";
				} else {
					$("current_label").innerHTML = site_ver;
					$("nv_frame").style.display = "";
				}
			}
		}
	};
	xmlhttp.send();
}



/*
 *
 */
if (isWidget)
{
	widget.onremove = remove;
	widget.onhide = hide;
	widget.onshow = show;
}
